// 全局变量
let addressList = [];
let checkoutItems = [];
let selectedAddressId = null;
let selectedPaymentMethod = 'ONLINE';
let deliveryFee = 10.00; // 默认运费

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function () {
    // 加载公共头部和底部
    // loadCommonParts();

    // 初始化页面
    initPage();

    // 绑定事件
    bindEvents();
});


// 初始化页面
function initPage() {
    // 检查用户是否登录
    const token = localStorage.getItem('token');
    if (!token) {
        // 未登录，跳转到登录页
        window.location.href = './login.html?redirect=' + encodeURIComponent(window.location.href);
        return;
    }

    // 获取结算商品
    const checkoutItemsStr = localStorage.getItem('checkoutItems');
    if (!checkoutItemsStr) {
        // 没有结算商品，返回购物车页面
        layui.use('layer', function () {
            const layer = layui.layer;
            layer.msg('请先选择要结算的商品', { icon: 0 });
            setTimeout(() => {
                window.location.href = './cart.html';
            }, 1500);
        });
        return;
    }

    // 解析结算商品数据
    checkoutItems = JSON.parse(checkoutItemsStr);

    // 加载收货地址
    loadAddressList();

    // 加载商品信息
    renderProducts();

    // 计算订单金额
    calculateOrderAmount();
}

// 加载地址列表
function loadAddressList() {
    let userData = AuthService.getUserInfo().userData;
    // 使用静态地址数据，简化实现
    addressList = [
        {
            id: 1,
            receiverName: userData.nickname || userData.username,
            receiverPhone: userData.phone,
            province: userData.province,
            city: userData.city,
            district: userData.district,
            detailAddress: userData.address,
            zipCode: userData.zipCode,
            isDefault: true
        },
        // {
        //     id: 2,
        //     receiverName: '李四',
        //     receiverPhone: '13900139000',
        //     province: '上海市',
        //     city: '上海市',
        //     district: '浦东新区',
        //     detailAddress: '张江高科技园区18号',
        //     zipCode: '201203',
        //     isDefault: false
        // }
    ];

    // 默认选中第一个地址
    selectedAddressId = addressList[0].id;

    // 渲染地址列表
    renderAddressList();
}

// 渲染地址列表
function renderAddressList() {
    const addressListEl = document.querySelector('.address-list');
    if (!addressListEl) return;

    let html = '';
    addressList.forEach(address => {
        html += `
            <div class="address-item ${address.id === selectedAddressId ? 'selected' : ''}" data-id="${address.id}">
                <div class="address-name">${address.receiverName}</div>
                <div class="address-phone">${address.receiverPhone}</div>
                <div class="address-detail">${address.province} ${address.city} ${address.district} ${address.detailAddress}</div>
                <div class="address-actions">
                    ${address.isDefault ? '<span class="default-tag">默认地址</span>' : ''}
                </div>
            </div>
        `;
    });

    addressListEl.innerHTML = html;

    // 绑定地址选择事件
    document.querySelectorAll('.address-item').forEach(item => {
        item.addEventListener('click', function () {
            selectedAddressId = parseInt(this.getAttribute('data-id'));
            updateSelectedAddress();
        });
    });
}

// 更新选中的地址
function updateSelectedAddress() {
    document.querySelectorAll('.address-item').forEach(item => {
        const itemId = parseInt(item.getAttribute('data-id'));
        if (itemId === selectedAddressId) {
            item.classList.add('selected');
        } else {
            item.classList.remove('selected');
        }
    });
}

// 渲染商品信息
function renderProducts() {
    const productListEl = document.querySelector('.product-list');
    if (!productListEl) return;

    let html = `
        <table class="product-table">
            <thead>
                <tr>
                    <th class="product-info-col">商品信息</th>
                    <th class="price-col">单价</th>
                    <th class="quantity-col">数量</th>
                    <th class="subtotal-col">小计</th>
                </tr>
            </thead>
            <tbody>
    `;

    checkoutItems.forEach(item => {
        html += `
            <tr>
                <td class="product-info-col">
                    <div class="product-info">
                        <div class="product-image">
                            <img src="${item.book.image || './img/default-book.jpg'}" alt="${item.book.title}">
                        </div>
                        <div class="product-details">
                            <h4 class="product-title">${item.book.title}</h4>
                            <p class="product-author">${item.book.author || '未知作者'}</p>
                        </div>
                    </div>
                </td>
                <td class="price-col">
                    <div class="product-price">¥${item.book.price.toFixed(2)}</div>
                </td>
                <td class="quantity-col">
                    <div class="product-quantity">${item.quantity}</div>
                </td>
                <td class="subtotal-col">
                    <div class="product-subtotal">¥${item.subtotal.toFixed(2)}</div>
                </td>
            </tr>
        `;
    });

    html += `
            </tbody>
        </table>
    `;

    productListEl.innerHTML = html;
}

// 计算订单金额
function calculateOrderAmount() {
    // 商品总价
    const productTotal = checkoutItems.reduce((sum, item) => sum + item.subtotal, 0);

    // 运费
    const deliveryFee = 10.00; // 固定运费

    // 订单总价
    const orderTotal = productTotal + deliveryFee;

    // 更新订单汇总信息
    const summaryEl = document.querySelector('.order-summary');
    if (!summaryEl) return;

    summaryEl.innerHTML = `
        <div class="summary-item">
            <span>商品总价：</span>
            <span>¥${productTotal.toFixed(2)}</span>
        </div>
        <div class="summary-item">
            <span>运费：</span>
            <span>¥${deliveryFee.toFixed(2)}</span>
        </div>
        <div class="summary-item total">
            <span>应付总额：</span>
            <span class="final-price">¥${orderTotal.toFixed(2)}</span>
        </div>
        <div class="summary-actions">
            <button class="submit-order-btn" id="submitOrderBtn">提交订单</button>
        </div>
    `;
}

// 绑定事件
function bindEvents() {
    // 支付方式选择
    document.querySelectorAll('.payment-option').forEach(option => {
        option.addEventListener('click', function () {
            document.querySelectorAll('.payment-option').forEach(o => o.classList.remove('active'));
            this.classList.add('active');
            selectedPaymentMethod = this.getAttribute('data-method');
        });
    });

    // 提交订单按钮
    document.addEventListener('click', function (e) {
        if (e.target && e.target.id === 'submitOrderBtn') {
            submitOrder();
        }
    });
}

// 提交订单
function submitOrder() {
    // 验证是否选择了地址
    if (!selectedAddressId) {
        layui.use('layer', function () {
            const layer = layui.layer;
            layer.msg('请选择收货地址', { icon: 0 });
        });
        return;
    }

    // 获取选中的地址
    const address = addressList.find(addr => addr.id === selectedAddressId);
    if (!address) {
        layui.use('layer', function () {
            const layer = layui.layer;
            layer.msg('收货地址信息不完整', { icon: 0 });
        });
        return;
    }

    // 获取订单备注
    const remarkEl = document.querySelector('.remark-input textarea');
    const remark = remarkEl ? remarkEl.value.trim() : '';

    // 计算商品总价
    const totalProductAmount = checkoutItems.reduce((sum, item) => sum + item.subtotal, 0);


    ApiService.cart.removeCartItems(checkoutItems.map(d => d.id)).then(res => {
        if (res.data) {
            // 构建订单数据
            const orderData = {
                // addressId: selectedAddressId,
                paymentMethod: selectedPaymentMethod,
                remark: remark,
                items: checkoutItems.map(item => ({
                    bookId: item.book.id,
                    quantity: item.quantity,
                    price: item.book.price
                })),
                totalAmount: totalProductAmount + deliveryFee,
                deliveryFee: deliveryFee,
                address: `${address.province} ${address.city} ${address.district} ${address.detailAddress}`,
                phone: address.receiverPhone,
                // receiverName: address.receiverName
            };

            layui.use('layer', function () {
                const layer = layui.layer;
                const loadingIndex = layer.load(2);

                // 调用创建订单API
                ApiService.order.createOrder(orderData)
                    .then(response => {
                        layer.close(loadingIndex);

                        if (response.data) {
                            const orderId = response.data.id;

                            // 清除结算商品
                            localStorage.removeItem('checkoutItems');

                            // 显示订单创建成功提示
                            layer.msg('订单创建成功', { icon: 1 });

                            // 如果是在线支付，跳转到支付页面
                            if (selectedPaymentMethod === 'ONLINE') {
                                setTimeout(() => {
                                    window.location.href = `./payment.html?orderId=${orderId}`;
                                }, 1500);
                            } else {
                                // 货到付款，跳转到订单详情页
                                setTimeout(() => {
                                    window.location.href = `./order.html`;
                                }, 1500);
                            }
                        } else {
                            layer.msg('订单创建失败', { icon: 2 });
                        }
                    })
                    .catch(error => {
                        layer.close(loadingIndex);
                        console.error("创建订单失败:", error);
                        layer.msg('创建订单失败，请重试', { icon: 2 });
                    });
            });
        }
    })


}